package pe.com.manpower.sisplan.view.servlet;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.sql.Blob;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;


public class VerFoto extends HttpServlet {
   private static final String CONTENT_TYPE = "image/jpg; charset=utf-8";

   public void init(ServletConfig config) throws ServletException {
       super.init(config);

   }

   public void doGet(HttpServletRequest request, 
                     HttpServletResponse response) throws ServletException, 

                                                          IOException {

       response.setContentType(CONTENT_TYPE);
       response.setContentType(CONTENT_TYPE);
       String noCia=request.getParameter("pNoCia");
       String codTrab=request.getParameter("pCodTrab");
      
       OutputStream os = response.getOutputStream();
       Connection conn = null; 
     

       try {
           Context ctx = new InitialContext();
           DataSource ds = (DataSource)ctx.lookup("jdbc/ConnSisplanDS");

           conn = ds.getConnection();
           PreparedStatement statement = conn.prepareStatement(
             "SELECT 0 num,FOTO " + 
             "FROM  SISPLAN.PLM_TRAB_FOTO " +
             "WHERE NO_CIA = ?" + 
             "   AND COD_TRAB = ?" +
             "UNION ALL " +
             "SELECT 1 num,TRAB_FOTO_DEFAULT FOTO " +    
             "FROM SISPLAN.PLM_CONFIGURACIONES " +
             "WHERE NO_CIA = ? " +
             "ORDER BY 1 "   
             );

   
           statement.setString(1,noCia);            
           statement.setString(2,codTrab);
           statement.setString(3,noCia);
           
           ResultSet rs = statement.executeQuery(); 
           

           if (rs.next()) { 
               Blob blob = rs.getBlob("FOTO"); 

               BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream()); 
               int b; byte[] buffer = new byte[10240]; 

               while ((b = in.read(buffer, 0, 10240)) != -1) { os.write(buffer, 0, b); } 
               os.close();

           }
       } catch (Exception e){
           e.printStackTrace();

       } finally {
           try{
               if (conn != null){

                    conn.close();
               }

            } catch (SQLException sqle){
                sqle.printStackTrace();

            }  
       }

   }
}
